#! /usr/bin/python
from chimera.core.cli import ChimeraCLI, action, ParameterType
import datetime
from chimera.core.exceptions import ChimeraException, printException

import sys

class ExtinctionCLI(ChimeraCLI):
    def __init__(self):
        ChimeraCLI.__init__(self, "chimera-ext", "Extinction coefficient controller script", 0.1)
        self.addHelpGroup("Extinction", "Extinction")
        self.addController(name="ext", cls="Extinction", required=True, helpGroup="Extinction", help="Module to calculate extinction")
        self.addParameters(dict(name="time", short="t", long="time", type="string", default=None, helpGroup="Extinction", help="Time the observations took place (Required)"),
                           dict(name="plotFile", long="plotFile", type="string", default=None, helpGroup="Extinction", help="File where plot will be saved"),
                           dict(name="amLbound", long="amLbound", type="float", default=None, helpGroup="Extinction", help="Airmass lower bound"),
                           dict(name="amUbound", long="amUbound", type="float", default=None, helpGroup="Extinction", help="Airmass upper bound"),
			   dict(name="filter", short="f", long="filter", type="string", default='V', helpGroup="Extinction", help="Filter to use, defaults to V"),
                           dict(name="magLbound", long="magLbound", type="float", default=None, helpGroup="Extinction", help="Magnitude lower bound"),
                           dict(name="magUbound", long="magUbound", type="float", default=None, helpGroup="Extinction", help="Magnitude upper bound"),
                           dict(name="colorLbound", long="colorLbound", type="float", default=None, helpGroup="Extinction", help="Color lower bound"),
                           dict(name="colorUbound", long="colorUbound", type="float", default=None, helpGroup="Extinction", help="Color upper bound"),
                           dict(name="compareMags", long="compareMags", type=ParameterType.BOOLEAN, default=False, helpGroup="Extinction", help="Generate file showing magnitude comparisons"))

    @action(type="string", helpGroup="Extinction", help="Calculate 1st-order extinction coefficient using stars in a catalog")
    def fit1(self, options):
	filter=options.filter
        time = self.getTime(options)
        if time == None:
            print "Time not specified"
        elif options.fit1 == None:
            print "Catalog not specified"
        else:
            try:
                print self.ext.getExtCatalog1stOrder(filter, time, options.fit1,
                                                     options.plotFile,
                                                     options.amLbound,
                                                     options.amUbound,
                                                     options.magLbound,
                                                     options.magUbound,
                                                     options.compareMags)
            except Exception,e:
                printException(e)

    @action(type="string", helpGroup="Extinction", help="Calculate 2nd-order extinction coefficient using stars in a catalog")
    def fit2(self, options):
        time = self.getTime(options)
	filter = options.filter
        if time == None:
            print "Time not specified"
        elif options.fit2 == None:
            print "Catalog not specified"
        else:
            try:
                print self.ext.getExtCatalog2ndOrder(filter, time, options.fit2,
                                                     options.plotFile,
                                                     options.amLbound,
                                                     options.amUbound,
                                                     options.magLbound,
                                                     options.magUbound,
                                                     options.colorLbound,
                                                     options.colorUbound,
                                                     options.compareMags)
            except Exception,e:
                printException(e)

    @action(type="string", helpGroup="Extinction", help="Calculate extinction coefficient for a list of stars without catalog data")
    def fitNon(self, options):
        time = self.getTime(options)
	filter = options.filter
        if time == None:
            print "Time not specified"
        elif options.fitNon == None:
            print "Star list file or catalog not specified"
        else:
            try:
                print self.ext.getExtNonCatalog(filter, time, options.fitNon,
                                                options.plotFile,
                                                options.amLbound,
                                                options.amUbound,
                                                options.magLbound,
                                                options.magUbound)
		"""

		# We've now received the output of extinction module and have stored it as a dictionary. We now alphabetize our m0's and print them out, as well as the k and Corelation constant values. 
		m0list=[]
		print '\n'
		for element in dictionary:
			if ((element != 'k') and (element != 'Corelation Constant')):
				print 'Wakakaka'#element+': '+dictionary[element]
		print '\n'
		print 'k: '+str(dictionary['k'])
		print 'Corelation Constant: '+ str(dictionary['Corelation Constant'])
				
		"""			

            except Exception,e:
                printException(e)

    def getTime(self, options):
        if options.time == None:
            return None
        else:
	  try:
	    try:
	    	try:
			obstime=datetime.datetime.strptime(options.time,'%Y-%m-%dT%H:%M:%S.%f')
		except:
			obstime=datetime.datetime.strptime(options.time,'%Y-%m-%dT%H:%M:%S')
	    except:
		obstime=datetime.datetime.strptime(options.time,'%Y-%m-%dT%H:%M')
	  except:
	    obstime=datetime.datetime.strptime(options.time,'%Y%m-%dT%H:%M') #Put in any new needed format here.
          
	return obstime

def main():
    cli = ExtinctionCLI()
    cli.run(sys.argv)
    cli.wait()

if __name__ == '__main__':
    main()
